package utills;


import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author quan
 * @Description 数据库连接的工具类
 * @Date 2023/6/30 15:57
 */
public class DBUtils {
    //1、定义数据源
    private static DataSource dataSource;
    //定义三个属性
    private static final String URL = "jdbc:mysql://localhost:3306/blog_db?characterEncoding=utf8&useSSL=false";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";
    //2、完成数据的初始化
    static {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(USER);
        mysqlDataSource.setPassword(PASSWORD);
        dataSource = mysqlDataSource;
    }
    //3、构造方法私有化
    private DBUtils(){};
    //4、构造一个连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    //5、依次关闭连接，释放资源
    public static void close(PreparedStatement statement, Connection connection, ResultSet resultSet){
        if((resultSet != null)){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection !=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
